<template>
  <div>
    <el-drawer class="dia-style" :title="title" :visible.sync="isOpen" width="60%" :close-on-click-modal="false" size="50%" :wrapper-closable="false">
      <el-col :span="24">
        <div class="tips">基础信息</div>
      </el-col>
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="140px" @submit.native.prevent>
        <el-form-item label="数据源名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入数据源名称" maxlength="50" />
        </el-form-item>
        <el-form-item class="el-custom-item" label="数据源类型" prop="sourceType">
          <div v-for="(item,index) in dataType" :key="index" class="card-container" :class="{ active: formData.sourceType == item.keyValue}" @click="handleChangeDataType(item.keyValue)">
            <div class="card-pic">
              <img
                style="width: 26px; height:26px;vertical-align:middle"
                :src="item.iconUrl || require('@/assets/images/sjjr_jrsjy_01.png')"
                alt=""
              >
            </div>
            <div class="card-text hk-flex">
              <p class="card-title">{{ item.name }}</p>
            </div>
            <label v-if="formData.sourceType == item.keyValue" class="el-form-list__item-status-label"><i class="el-icon-upload-success el-icon-check" /></label>
          </div>
        </el-form-item>
        <el-form-item label="编码格式" prop="decoding">
          <div class="btn-wk">
            <el-button v-for="(i,index) in wayData" :key="index" :class="[formData.decoding==i.field?'active-btn':'','custom-btn']" @click="hancdleChangeWay(i.field)">{{ i.field }}</el-button>
          </div>
        </el-form-item>
        <el-form-item class="datasource-form">
          <template slot="label"><span>接入产品</span></template>
          <div class="mb20">
            <el-button icon="el-icon-thumb" style="margin-right: 20px" @click="handleSelectData">请选择</el-button>
          </div>
          <div v-for="(item,index) in importProduct" :key="item.id" class="table-list hk-flex">
            <div class="table-list-l">
              <img class="list-img" :src="item.companyLogo || require('@/assets/images/sjjr_jrsjy_all.png')" alt="">
            </div>
            <div class="table-list-c" style="flex:1">
              <h4 class="table-tit">{{ item.productName }}</h4>
              <div class="table-cont hk-flex">
                <div class="flex-1"><span>类型：</span>{{ item.productType?item.productType:'-' }}</div>
                <div class="flex-1"><span>版本：</span>{{ item.version?item.version:'-' }}</div>
              </div>
            </div>
            <div class="table-list-r">
              <i class="el-icon-delete" style="cursor: pointer;" @click="handleDelete(item, index)" />
            </div>
          </div>
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <div class="tips">配置信息</div>
          </el-col>
          <!--    消息队列      -->
          <template v-if="dataSourceType == 'Kafka'">
            <el-col :span="12">
              <el-form-item label="Kafka服务IP" prop="ip">
                <el-input v-model="formData.ip" placeholder="请输入Kafka服务IP" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="端口号" prop="port">
                <el-input v-model="formData.port" placeholder="请输入端口号" maxlength="5" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Topic" prop="connectInfo.topic">
                <el-input v-model="formData.connectInfo.topic" placeholder="请输入Topic" maxlength="40" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="消费组ID" prop="connectInfo.groupId">
                <el-input v-model="formData.connectInfo.groupId" placeholder="请输入消费组ID" maxlength="40" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="formData.username" placeholder="请输入用户名" maxlength="40" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码" prop="password">
                <el-input v-model="formData.password" type="password" placeholder="请输入密码" maxlength="40" />
              </el-form-item>
            </el-col>
          </template>
          <!--    ES      -->
          <template v-if="dataSourceType == 'ES'">
            <el-col :span="12">
              <el-form-item label="ES接收端IP" prop="ip">
                <el-input v-model="formData.ip" placeholder="请输入ES服务IP" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="协议类型" prop="connectInfo.protocol">
                <el-select v-model="formData.connectInfo.protocol" placeholder="请选择协议类型">
                  <el-option
                    v-for="item in protocolOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服务端口" prop="port">
                <el-input v-model="formData.port" placeholder="请输入ES服务端口" maxlength="5" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="索引名称" prop="indexName">
                <el-input v-model="formData.connectInfo.indexName" placeholder="请输入索引名称" maxlength="40" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="ES用户名" prop="username">
                <el-input v-model="formData.username" placeholder="请输入ES用户名" maxlength="40" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="ES密码" prop="password">
                <el-input v-model="formData.password" type="password" placeholder="请输入ES密码" maxlength="40" />
              </el-form-item>
            </el-col>
          </template>
          <!--     数据库     -->
          <template v-if="dataSourceType == 'JDBC'">
            <el-col :span="12">
              <el-form-item label="数据库类型" prop="connectInfo.databaseTypeId">
                <el-select v-model="formData.connectInfo.databaseTypeId" placeholder="请选择协议类型">
                  <el-option
                    v-for="item in databaseTypeOption"
                    :key="item.value"
                    :label="item.dataName"
                    :value="item.id"
                  />
                </el-select>
                <!-- <el-cascader
                  v-model="formData.connectInfo.databaseTypeId"
                  :options="databaseTypeOption"
                  :props="propsData"
                  :show-all-levels="false"
                  clearable
                /> -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据库名称" prop="connectInfo.databaseName">
                <el-input v-model="formData.connectInfo.databaseName" placeholder="请输入数据库名称" maxlength="40" />
              </el-form-item>
            </el-col>
            <!--            <el-col :span="12" v-show="hidden">
                          <el-form-item label="表名" prop="JSON.parse(connectInfo.tableName)">
                            <el-input v-model="JSON.parse(formData.connectInfo).tableName" placeholder="请输入表名"/>
                          </el-form-item>
                        </el-col>-->
            <el-col :span="12">
              <el-form-item label="数据库IP" prop="ip">
                <el-input v-model="formData.ip" placeholder="请输入数据库IP" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据库端口" prop="port">
                <el-input v-model="formData.port" placeholder="请输入数据库端口" maxlength="5" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据库用户名" prop="username">
                <el-input v-model="formData.username" placeholder="请输入数据库用户名" maxlength="40" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据库密码" prop="password">
                <el-input v-model="formData.password" type="password" placeholder="请输入密码" maxlength="40" />
              </el-form-item>
            </el-col>
          </template>
          <!--    HTTP      -->
          <template v-if="dataSourceType == 'HTTP'">
            <el-col :span="12">
              <el-form-item label="接口IP" prop="ip">
                <el-input v-model="formData.ip" placeholder="请输入接口IP" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="接口端口" prop="port">
                <el-input v-model="formData.port" placeholder="请输入接口端口" maxlength="5" />
              </el-form-item>
            </el-col>
            <!--            <el-col :span="12">
                          <el-form-item label="protocol" prop="protocol">
                            <el-input v-model="formData.connectInfo.protocol" placeholder="请输入接口端口"/>
                          </el-form-item>
                        </el-col>-->
          </template>
          <!--    系统日志      -->
          <template v-if="dataSourceType == 'Syslog'">
            <el-col :span="12">
              <el-form-item label="发送端IP" prop="sendIp">
                <el-input v-model="formData.sendIp" placeholder="请输入发送端IP" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服务IP" prop="ip">
                <el-input v-model="formData.ip" placeholder="请输入服务端IP" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="监听端口" prop="port">
                <el-input v-model="formData.port" placeholder="请输入监听端口" maxlength="5" />
              </el-form-item>
            </el-col>
          </template>
        </el-row>
      </el-form>
      <div class="el-drawer-footer">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>
    <SelectDialog ref="selectRef" title="选择接入数据" :check-data="importProduct" :is-multiple="false" @handleSubmit="dialogSubmitEvent" />
  </div>
</template>

<script>
import SelectDialog from '../../components/addProductSelector'
import { dataBaseList, addAccessData, editAccessData } from '@/api/milkyway/gatherData'

export default {
  components: { SelectDialog },
  props: {
    title: {
      type: String,
      default() {
        return '编辑'
      }
    },
    dataType: {
      type: Array,
      default() {
        return []
      }
    },
    form: {
      type: Object,
      default() {
        return {}
      }
    },
    sourceType: {
      type: String,
      default() {
        return 'Kafka'
      }
    },
    editInfo: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      // 数据库选择下拉框
      databaseTypeOption: [],
      // http请求
      protocolOptions: [
        { label: 'http', value: 'http' },
        { label: 'https', value: 'https' }
      ],
      propsData: { value: 'id', label: 'dataName', multiple: false },
      hidden: true,
      isOpen: false,
      showAddDialog: false,
      showSelectDialog: false,
      checkNodes: [],
      importProduct: [],
      formData: {
        connectInfo: {},
        decoding: 'UTF-8',
        sourceType: 'Kafka'
      },
      // 表单参数
      rules: {
        name: [{ required: true, message: '数据源名称不能为空', trigger: 'blur' }],
        sourceType: [{ required: true, message: '请选择数据源类型', trigger: 'blur' }],
        decoding: [{ required: true, message: '请选择编码格式', trigger: 'blur' }],
        importProduct: [{ required: true, message: '请选择接入产品', trigger: 'blur' }],
        sendIp: [
          { required: true, message: '请输入发送端IP', trigger: 'blur' },
          {
            pattern:
              /^(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9]))$/,
            message: '请输入正确的IP地址',
            trigger: 'blur'
          }
        ],
        serveIP: [
          { required: true, message: '请输入服务端IP', trigger: 'blur' },
          {
            pattern:
              /^(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9]))$/,
            message: '请输入正确的IP地址',
            trigger: 'blur'
          }
        ],
        ip: [
          { required: true, message: '请输入服务IP', trigger: 'blur' },
          {
            pattern:
              /^(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9]))$/,
            message: '请输入正确的IP地址',
            trigger: 'blur'
          }
        ],
        port: [
          { required: true, message: '请输入端口号', trigger: 'blur' },
          {
            pattern: /^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{4}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/,
            message: '请输入正确的端口号',
            trigger: 'blur'
          }
        ],
        'connectInfo.topic': [{ required: true, message: '请输入topic', trigger: 'blur' }],
        'connectInfo.groupId': [{ required: true, message: '请输入消费组ID', trigger: 'blur' }],
        'connectInfo.databaseTypeId': [{ required: true, message: '请选择数据库类型', trigger: 'blur' }]
      },
      dataSourceType: this.sourceType || 'Kafka',
      wayData: [
        { field: 'UTF-8' },
        { field: 'GBK' },
        { field: 'UTF-16' }
      ]
    }
  },
  watch: {
    form: {
      handler(newVal) {
        if (newVal.id) {
          this.formData = JSON.parse(JSON.stringify(newVal))
          this.dataSourceType = this.sourceType
        } else {
          console.log(this.sourceType ? this.sourceType : 'Kafka')
          this.formData = JSON.parse(JSON.stringify(newVal))
          this.$set(this.formData, 'decoding', 'UTF-8')
          this.$set(this.formData, 'sourceType', this.sourceType ? this.sourceType : 'Kafka')
          this.dataSourceType = this.sourceType || 'Kafka'
        }
      },
      deep: false,
      immediate: true
    },
    editInfo: {
      handler(newVal) {
        if (newVal?.companyInfos && newVal?.companyInfos.length > 0) {
          this.importProduct = newVal.companyInfos
        }

        if (newVal?.dataSource?.connectInfo) {
          const connectValue = newVal.dataSource.connectInfo
          try {
            this.formData.connectInfo = JSON.parse(connectValue)
          } catch {}
        }
      },
      deep: false,
      immediate: true
    },
    importProduct: {
      handler(val) {
        if (val.length > 0) {
          this.formData.importProduct = val
          this.$refs.formRef && this.$refs.formRef.clearValidate('importProduct')
        } else {
          this.formData.importProduct = []
          this.$refs.formRef && this.$refs.formRef.validateField('importProduct')
        }
      },
      deep: true
    }
  },
  created() {
    this.dataBaseList()
  },
  methods: {
    /** 显示弹窗*/
    show() {
      this.isOpen = true
      this.reset()
    },
    reset() {
      this.importProduct = []
      this.resetForm('formRef')
    },
    /** 获取数据库列表 */
    dataBaseList() {
      dataBaseList().then((res) => {
        this.databaseTypeOption = res
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['formRef'].validate((valid) => {
        if (this.importProduct.length > 0) {
          this.formData.importProduct = 'true'
          this.$refs.formRef && this.$refs.formRef.clearValidate('importProduct')
        } else {
          this.formData.importProduct = ''
        }
        if (valid) {
          if (this.importProduct.length == 0) {
            this.$message.error('请选择接入产品')
            return false
          }
          const companyInfos = this.importProduct.map((i) => ({
            id: i.id
          }))
          let allData = {}
          let dataSource = {}
          if (this.dataSourceType == 'Kafka') {
            dataSource = {
              ...this.formData,
              sourceType: this.dataSourceType
            }
            dataSource.connectInfo = JSON.stringify(dataSource.connectInfo)
            allData = Object.assign({}, { dataSource: dataSource, companyInfos: companyInfos })
          } else if (this.dataSourceType == 'JDBC') {
            dataSource = {
              ...this.formData,
              sourceType: this.dataSourceType,
              tableName: ''
            }
            dataSource.connectInfo = JSON.stringify(dataSource.connectInfo)
            allData = Object.assign({}, { dataSource: dataSource, companyInfos: companyInfos })
          } else if (this.dataSourceType == 'Syslog') {
            dataSource = {
              ...this.formData,
              sourceType: this.dataSourceType
            }
            dataSource.connectInfo = JSON.stringify({
              sendIp: this.formData.sendIp
            })
            allData = Object.assign({}, { dataSource: dataSource, companyInfos: companyInfos })
          } else if (this.dataSourceType == 'HTTP') {
            dataSource = {
              ...this.formData,
              sourceType: this.dataSourceType,
              proyocol: 'http'
            }
            dataSource.connectInfo = JSON.stringify(dataSource.connectInfo)
            allData = Object.assign({}, { dataSource: dataSource, companyInfos: companyInfos })
          } else {
            dataSource = {
              ...this.formData,
              sourceType: this.dataSourceType
            }
            dataSource.connectInfo = JSON.stringify(dataSource.connectInfo)
            allData = Object.assign({}, { dataSource: dataSource, companyInfos: companyInfos })
          }
          if (this.formData.id != undefined) {
            editAccessData(allData)
              .then((res) => {
                this.$modal.msgSuccess('修改成功')
                this.isOpen = false
                this.importProduct = []
                this.$emit('changeOpen', false)
              })
              .catch((error) => {})
          } else {
            addAccessData(allData).then((res) => {
              this.$modal.msgSuccess('新增成功')
              this.isOpen = false
              this.importProduct = []
              this.$emit('changeOpen', false)
            })
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.isOpen = false
      this.importProduct = []
      this.formData.sourceType = 'Kafka'
      this.formData.decoding = 'UTF-8'
    },
    /** 删除按钮操作 */
    handleDelete(data, index) {
      // this.importProduct = []
      this.importProduct.splice(index, 1)
      if (this.importProduct.length == 0) {
        this.formData.importProduct = this.importProduct
        this.$refs.formRef && this.$refs.formRef.validateField('importProduct')
      }
    },
    /**  点击 ‘请选择’ **/
    handleSelectData() {
      this.$refs.selectRef.show(this.importProduct)
    },
    /** 关闭弹窗*/
    dialogSubmitEvent(data) {
      this.importProduct = data
    },
    /** 切换数据源类型 */
    handleChangeDataType(key) {
      this.formData.sourceType = key
      this.dataSourceType = key
      this.$refs.formRef.clearValidate()
    },
    /** 切换编码格式按钮 */
    hancdleChangeWay(key) {
      this.activeBtn = key
      this.formData.decoding = key
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-select{
  width:100% !important;
}
.active {
  border-color: #2979ff;
  // background: #e4eeff;
}
.card-container{
  margin-right:20px;
  margin-bottom:10px;
  &:nth-last-child(1),&:nth-last-child(2){
    margin-bottom:0;
  }
}
::v-deep .el-table__body-wrapper {
  height: 200px !important;
  overflow-y: auto !important;
}
.el-cascader {
  width: 100%;
}

.el-form-item__label {
  width: 140px !important;
}

.el-form-item__content {
  margin-left: 140px !important;
}
.table-cont{
  justify-content: space-between;
  .flex-1{
    flex:1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-right:10px;
  }
}
::v-deep .datasource-form .el-form-item__label::after{
  content:'*' !important;
  color: #ff4949;
  margin-left: 6px;
}
</style>
